<template>
  <!-- 修改密码 -->
  <el-dialog
      title="修改密码"
      :close-on-click-modal="false"
      v-model="dialogVisible"
      width="30%"
      @close="handleClose"
  >
    <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleFormRef"
        label-width="100px"
    >
      <el-form-item label="旧密码：" prop="oldPassword">
        <el-input
            maxlength="50"
            type="password"
            v-model="ruleForm.oldPassword"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="新的密码：" prop="password">
        <el-input
            maxlength="50"
            type="password"
            v-model="ruleForm.password"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="确认密码：" prop="confirmPassword">
        <el-input
            maxlength="50"
            type="password"
            v-model="ruleForm.confirmPassword"
            autocomplete="off"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submit">提 交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
const httpService = inject("httpService")

// 弹窗显隐
const dialogVisible = ref(false)

// 表单数据
const ruleForm = reactive({
  oldPassword: '',
  password: '',
  confirmPassword: ''
})

// 表单校验规则
const rules = {
  oldPassword: [
    {required: true, message: '请输入旧密码', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 6, message: '密码至少6位', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请确认新密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== ruleForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 表单 ref
const ruleFormRef = ref(null)

// 提交处理
const submit = () => {
  ruleFormRef.value.validate(valid => {
    if (valid) {
      ElMessageBox.confirm('是否确认修改密码？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        httpService.post("/sys-user/updatePassword", ruleForm).then(() => {
          ElMessage.success('密码修改成功')
          dialogVisible.value = false
          resetForm()
        })
      }).catch(() => {})
    }
  })
}

// 外部调用显示弹窗的方法
const openDia = () => {
  dialogVisible.value = true
  resetForm()
}

// 重置表单
const resetForm = () => {
  ruleFormRef.value?.resetFields()
}

// 弹窗关闭
const handleClose = () => {
  resetForm()
}

// 向外暴露方法
defineExpose({
  openDia
});

</script>

<style scoped>
</style>
